package com.neu.cpsp.controller;
/*
    @author neu.xiangwenjuan
    @create 2022/3/28
*/

import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.cpsp.dao.TeamGroupMapper;
import com.neu.cpsp.pojo.*;
import com.neu.cpsp.service.*;
import com.neu.cpsp.util.ExportExcelUtils;
import com.neu.cpsp.util.JWTUtils;
import com.neu.cpsp.util.result.Result;
import com.neu.cpsp.util.result.ResultGenerator;

import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.nio.channels.spi.SelectorProvider;
import java.text.DecimalFormat;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/evaluateRecord")
public class EvaluateRecordController {

    @Autowired
    private EvaluateRecordService evaluateRecordService;

    @Autowired
    private PerformanceHistoryService performanceHistoryService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private RegulationDetailService regulationDetailService;

    @Autowired
    private EvaluateRecordToEmployeeService evaluateRecordToEmployeeService;

    private EmployeeController employeeController = new EmployeeController();

    @ApiOperation("获得违章记录")
    @RequestMapping(value = "/getEvaluateRecord", method = RequestMethod.GET)
    @ResponseBody
    private Result getEvaluateRecordInfo(@RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "10") Integer pageSize,
                                         HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        // 得到用户的工号，确认部门，根据角色判断用户权限。
        String role = verify.getClaim("role").asString();
        String jobNumber = verify.getClaim("jobNumber").asString();
        EmployeeEntity employee = employeeService.selectByJobNumber(jobNumber);
        // 得到该用户所在部门的员工的idCard。
        List<String> idCardList = employeeService.selectCardByDepart(employee.getDepartment().getDepartmentId());
        PageHelper.startPage(pageNum,pageSize);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int session = employeeController.getSeason(new Date());

        List<EvaluateRecord> list = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision")) {
            list = evaluateRecordService.selectEvaluateRecords(year, session);
        }else if (role.equals("department")) {
            list = evaluateRecordService.selectEvaluateRecordsByDepart(idCardList);
        }

        PageInfo pageInfo = PageInfo.of(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation("获取修改前违章记录")
    @RequestMapping(value = "/getUpdateEvaluateRecord", method = RequestMethod.POST)
    @ResponseBody
    private Result getInfoBeforeUpdate(Integer evaluateRecordId) {
        // 得到关联人员的信息
        List<EvaluateRecordRelated> list = evaluateRecordToEmployeeService.selectRelatedEmployees(evaluateRecordId);
        return ResultGenerator.genSuccessResult(list);
    }

    @ApiOperation("删除关联人员")
    @RequestMapping(value = "/deleteRelatedEmployee", method = RequestMethod.POST)
    @ResponseBody
    private Result deleteRelatedEmployee(Integer id) {
        int count = evaluateRecordToEmployeeService.deleteRelatedEmployee(id);
        if (count > 0) {
            return ResultGenerator.genSuccessResult("数据删除成功！");
        }else {
            return ResultGenerator.genFailResult("数据删除失败！");
        }
    }

    /**
     * 只能修改比例
     * @param id
     * @param proportionOfPunishment
     * @return
     */
    @ApiOperation("修改关联人员扣减比例")
    @RequestMapping(value = "/updateEvaluateRecordProp", method = RequestMethod.POST)
    @ResponseBody
    private Result updateEvaluateRecord( Integer id, Double proportionOfPunishment) {
        int count = evaluateRecordToEmployeeService.updateByPrimaryId(id, proportionOfPunishment);
        if (count > 0){
            return ResultGenerator.genSuccessResult("数据修改成功！");
        }else {
            return ResultGenerator.genFailResult("数据修改失败！");
        }
    }

    @ApiOperation("导出季度汇总记录")
    @RequestMapping(value = "/loadEvaluateRecord", method = RequestMethod.POST)
    @ResponseBody
    private Result loadEvaluateRecord(HttpServletRequest request) {
        // 得到数据
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        // 得到用户的工号，确认部门，根据角色判断用户权限。
        String role = verify.getClaim("role").asString();
        String jobNumber = verify.getClaim("jobNumber").asString();
        EmployeeEntity employee = employeeService.selectByJobNumber(jobNumber);
        List<EvaluateRecordDepart> result = new ArrayList<>();
        if (role.equals("department")) {// 部门领导，本部门的，按照班组筛选。

            EvaluateRecordDepart depart = getInfoByDepart(employee.getDepartment().getDepartmentId(),employee.getDepartment().getDepartmentName());
            result.add(depart);
        }else if(role.equals("admin") || role.equals("leader") || role.equals("supervision")) {
            // 所有部门的信息
            List<Department> departments = departmentService.selectAll();
            EvaluateRecordDepart depart = new EvaluateRecordDepart();
            for (Department department:departments) {
                depart = getInfoByDepart(department.getDepartmentId(),department.getDepartmentName());
                result.add(depart);
            }
        }
        return ResultGenerator.genSuccessResult(result);
    }

    // 工具方法
    /**
     * 输入一个departmentId 返回一个map。
     */
    private EvaluateRecordDepart getInfoByDepart (String departmentId, String departmentName) {
        List<EvaluateRecordVO> list = new ArrayList<>();


        // 得到当前年份和季度。
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = employeeController.getSeason(new Date());
        // 得到在当前季度每个员工因为违规所扣除的绩效比例的总和。
        List<EvaluateRecordCurrentQuarter> sumProp = evaluateRecordService.getSumProp(year,quarter);

        DecimalFormat decFormat = new DecimalFormat("#%");

        List<String> idCardList = employeeService.selectCardByDepart(departmentId);
        // 根据employee的部门查找相应信息。
        // 得到员工数据
        List<EmployeeEntity> employees = employeeService.selectEmployeesByDepartment(departmentId);
        // 当前季度初始绩效
        List<PerformanceHistory> currentPerformance = performanceHistoryService.selectPerformanceValue(year, quarter);
        for (EmployeeEntity employeeEntity:employees) {
            EvaluateRecordVO evaluateRecordVO = new EvaluateRecordVO();
            evaluateRecordVO.setEmployeeName(employeeEntity.getName());
            evaluateRecordVO.setEmployeeIdCard(employeeEntity.getIdCard());
            evaluateRecordVO.setIs45Days(employeeEntity.getIs45Days());
            if (employeeEntity.getIsDirectProducer() != null) {
                if (employeeEntity.getIsDirectProducer() == 1) {
                    evaluateRecordVO.setIsDirectProducer("生产岗");
                    evaluateRecordVO.setIncreaseMoney(100);
                }else if (employeeEntity.getIsDirectProducer() == 2) {
                    evaluateRecordVO.setIsDirectProducer("辅助岗");
                    evaluateRecordVO.setIncreaseMoney(50);
                }else {
                    evaluateRecordVO.setIsDirectProducer("其他岗位");
                    evaluateRecordVO.setIncreaseMoney(0);
                }
            }else {
                evaluateRecordVO.setIncreaseMoney(0);
            }

            evaluateRecordVO.setPositionType(employeeEntity.getPositionType());
            if (employeeEntity.getTeamGroup() != null) {
                evaluateRecordVO.setTeamGroup(employeeEntity.getTeamGroup().getTeamGroupName());
            }
            for (PerformanceHistory performance:currentPerformance) {
                if (performance.getEmployeeIdCard().equals(employeeEntity.getIdCard())) {
                    evaluateRecordVO.setLastMoney(performance.getPerformanceValue());
                }else {
                    evaluateRecordVO.setLastMoney(0);
                }
            }
            for (EvaluateRecordCurrentQuarter record : sumProp) {
                if (employeeEntity.getIdCard().equals(record.getEmployeeIdCard())) {
                    evaluateRecordVO.setEvaCount(record.getEmployeeCount());
                    evaluateRecordVO.setEvaName("");
                    evaluateRecordVO.setIncreaseMoney(0);
                    if (record.getSumProp() >= 1) {
                        evaluateRecordVO.setProp(decFormat.format(100));
                        evaluateRecordVO.setPropMoney(evaluateRecordVO.getLastMoney());
                        evaluateRecordVO.setNextMoney(0);
                    } else {
                        evaluateRecordVO.setProp(decFormat.format(record.getSumProp()));
                        evaluateRecordVO.setPropMoney(evaluateRecordVO.getLastMoney() * record.getSumProp());
                        evaluateRecordVO.setNextMoney(evaluateRecordVO.getLastMoney() - evaluateRecordVO.getPropMoney());
                    }
                    evaluateRecordVO.setMonthMoney(evaluateRecordVO.getNextMoney());
                    evaluateRecordVO.setSumMoney(evaluateRecordVO.getNextMoney() * 3);
                }
            }
            evaluateRecordVO.setProp(decFormat.format(0));
            evaluateRecordVO.setPropMoney(0);
            evaluateRecordVO.setNextMoney(evaluateRecordVO.getLastMoney() + evaluateRecordVO.getIncreaseMoney());
            evaluateRecordVO.setMonthMoney(evaluateRecordVO.getNextMoney());
            evaluateRecordVO.setSumMoney(evaluateRecordVO.getMonthMoney() * 3);
            list.add(evaluateRecordVO);
        }
        EvaluateRecordVO total = new EvaluateRecordVO();
        for (EvaluateRecordVO recordVO : list) {
            total.setLastMoney(total.getLastMoney() + recordVO.getLastMoney());
            if (total.getIncreaseMoney() == null) {
                total.setIncreaseMoney(recordVO.getIncreaseMoney());
            }else {
                total.setIncreaseMoney(total.getIncreaseMoney() + recordVO.getIncreaseMoney());
            }
            total.setNextMoney(total.getNextMoney() + recordVO.getNextMoney());
            total.setMonthMoney(total.getMonthMoney() + recordVO.getMonthMoney());
            total.setSumMoney(total.getSumMoney() + recordVO.getSumMoney());
        }
        // 得到了list存储着整个部门的信息
        EvaluateRecordTeam evaluateRecordTeam = new EvaluateRecordTeam();
        evaluateRecordTeam.setTeamGroupName("总表");
        evaluateRecordTeam.setDataList(list);
        evaluateRecordTeam.setTotal(total);
        ArrayList<EvaluateRecordTeam> teamList = new ArrayList<>();
        teamList.add(evaluateRecordTeam);

        List<TeamGroup> teamGroupList = teamGroupMapper.findTeamGroupByDepart(departmentId);
        for (TeamGroup teamGroup : teamGroupList) {
            EvaluateRecordVO subTotal = new EvaluateRecordVO();
            List<EvaluateRecordVO> teamLists = new ArrayList<>();
            double lastMoney = 0,  nextMoney = 0, monthMoney = 0, sumMoney = 0;
            Integer increaseMoney = 0;
            for (EvaluateRecordVO evaluateRecordVO1:list) {
                if (evaluateRecordVO1.getTeamGroup() != null && evaluateRecordVO1.getTeamGroup().equals(teamGroup.getTeamGroupName())) {
                    teamLists.add(evaluateRecordVO1);
                    lastMoney += evaluateRecordVO1.getLastMoney();
                    increaseMoney += evaluateRecordVO1.getIncreaseMoney();
                    nextMoney += evaluateRecordVO1.getNextMoney();
                    monthMoney += evaluateRecordVO1.getMonthMoney();
                    sumMoney += evaluateRecordVO1.getSumMoney();
                }
            }
            EvaluateRecordTeam recordTeam = new EvaluateRecordTeam();
            subTotal.setLastMoney(lastMoney);
            subTotal.setIncreaseMoney(increaseMoney);
            subTotal.setNextMoney(nextMoney);
            subTotal.setMonthMoney(monthMoney);
            subTotal.setSumMoney(sumMoney);
            recordTeam.setTeamGroupName(teamGroup.getTeamGroupName());
            recordTeam.setDataList(teamLists);
            recordTeam.setTotal(subTotal);
            teamList.add(recordTeam);
        }
        EvaluateRecordDepart depart = new EvaluateRecordDepart();

        depart.setDepartmentName(departmentName);
        depart.setDepartList(teamList);

        return depart;
    }


}
